//树形数据

// 一般的树形数据 都有这些选项：id  pid

let tree = [
  {
    id: 1,
    title: "主页",
    children: [
      {
        id: 3,
        //pid 代表父节点
        pid: 1,
        title: "欢迎",
      },
      {
        id: 4,
        pid: 1,
        title: "学员管理",
        children: [
          {
            id: 5,
            pid: 4,
            title: "日志",
          },
        ],
      },
    ],
  },
  {
    id: 2,
    title: "用户中心",
  },
];

//树形数据扁平化
//循环判断(递归)，如果有children 就push继续往里面循环，直到没有children
function repeatTree(data) {
  let repeatArr = [];
  function recursion(data) {
    data.forEach((item) => {
      if (item.children) {
        recursion(item.children);
      }
      repeatArr.push({
        id: item.id,
        title: item.title,
        pid: item.pid ?? "",
      });
    });
  }
  recursion(data);
  return repeatArr;
}

let res = repeatTree(tree);
// console.log(res)

//扁平数据树形化
// 0:{id: 5, title: '日志', pid: 3}
// 1:{id: 3, title: '欢迎', pid: 1}
// 2:{id: 4, title: '学员管理', pid: 1}
// 3:{id: 1, title: '主页', pid: ''}
// 4:{id: 2, title: '用户中心', pid: ''}、

function convertTree(repeatArr) {
  let tree = [];
  repeatArr.forEach((item) => {
    //爸爸在哪儿 查找自己的父节点
    let parent = repeatArr.find((v) => item.pid === v.id);
    // console.log(parent)
    if (parent) {
      if (!parent.children) {
        parent.children = [];
      }
      parent.children.push(item);
    } else {
      tree.push(item);
    }
  });
  return tree;
}

let res2 = convertTree(res);
// console.log(res2)
